package com.owen.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    /**
     * 测试Controller
     * @return
     */
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        System.out.println("访问成功！");
        return "Hello Controller!";
    }

    /**
     * 测试thymeleaf是否可用
     * @param model
     * @return
     */
    @RequestMapping("/test")
    public String thymeleaf(Model model){
        // 把数据存入model
        model.addAttribute("name","owen");
        return "test";
    }

    // 进入添加页面
    @RequestMapping("/add")
    public String add(){
        return "user/add";
    }

    // 进入添加页面
    @RequestMapping("/update")
    public String update(){
        return "user/update";
    }

    // 进入登录页面
    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    // 执行登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String gologin(String name,String password,Model model){
        // 使用Shiro编写认证操作
        // 获取Subject
        Subject subject = SecurityUtils.getSubject();
        // 封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(name,password);
        // 执行登录方法
        try{
            subject.login(token);
            // 该代码无任何异常，表示登录成功
            return "redirect:/test";
        }catch (UnknownAccountException e){
            // 代表用户名不存在
            model.addAttribute("msg","用户名不存在！");
            return "login";
        }catch (IncorrectCredentialsException e){
            // 密码错误
            model.addAttribute("msg","密码输入错误！");
            return "login";
        }

    }

}